import axios from "axios";
// 

// const host = window.location.host;
let baseURL = "http://ddc.lycent.cn/api/";
// create an axios instance
function getQueryString(name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}
if (getQueryString("ip") == 1) {
  baseURL = "/";
} else if (getQueryString("ip") == 2) {
  baseURL = "http://ddc.lycent.cn/api";
} else if (getQueryString("ip") == 3) {
  baseURL = "http://192.168.1.141/api";
} else if (getQueryString("ip") == 4) {
  baseURL = "http://192.168.1.64/api";
} else {
  // http://192.168.1.141/ http://localhost:8080/api/http://123.56.85.24:5000/api/
  baseURL = "http://localhost:8080/api/";
}

const service = axios.create({
  baseURL,
  timeout: 50000 // request timeout
});
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    // 如果有token 就携带tokon
    let token = window.localStorage.getItem("accessToken");
    if (token) {
      config.headers.common.Authorization = token;
    }
    return config;
  },
  error => Promise.reject(error)
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (response.status !== 200) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  error => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);
export default service;
